package com.example.eshop_ssm.controller;

import com.example.eshop_ssm.annotation.CheckLogin;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

@Controller
@RequestMapping("/PicLoadController")
public class PicLoadController {

    @RequestMapping("/picload")
    @ResponseBody
    @CheckLogin
    //添加图片要加@RequestParam
    public ArrayList<String> picLoad(@RequestParam(value = "book_logo_big",required = false) MultipartFile book_logo_big,
                                     @RequestParam(value = "book_logo_small",required = false) MultipartFile book_logo_small,
                                     @RequestParam(value = "pic_names",required = false) MultipartFile[] pic_names,
                        HttpServletRequest request) throws IOException {

        ArrayList<String> fileStringNemaList = new ArrayList<>();
        if(book_logo_big!=null && !book_logo_big.isEmpty()){
            String bookLogoBig = savePic(book_logo_big, request);
            fileStringNemaList.add(bookLogoBig);
        }

        if(book_logo_small!=null && !book_logo_small.isEmpty()){
            String bookLogoSmall = savePic(book_logo_small, request);
            fileStringNemaList.add(bookLogoSmall);
        }


        for (MultipartFile file:pic_names) {
            if (file!=null && !file.isEmpty()){
                String picName = savePic(file, request);
                fileStringNemaList.add(picName);
            }
        }
        return fileStringNemaList;

    }


    /**
     * 上传文件，返回文件名字
     * @param pic
     * @param request
     * @return
     * @throws IOException
     */
    private String savePic(MultipartFile pic, HttpServletRequest request) throws IOException {

        String name = pic.getOriginalFilename();//获取文件名
        String suffixName = name.substring(name.lastIndexOf("."), name.length());//获取文件后缀名

        //获取文件夹在tomcat实际路径
        String picUpload = request.getServletContext().getRealPath("/picUpload");
        //System.out.println(picUpload);
        //给文件命名,防止重复
        String fileName = System.currentTimeMillis() + "" + ((int) Math.random() * 1000) + suffixName;

        //写出，write方法需要一个File对象
        File file = new File(picUpload + "\\" + fileName);
        pic.transferTo(file);

        return fileName;

    }
}
